package com.moss.cloud.auth.biz.service;

import com.moss.cloud.auth.biz.exception.AuthErrorType;
import com.moss.cloud.auth.biz.model.UserPrincipal;
import com.moss.cloud.auth.biz.utils.AuthHandel;
import com.moss.cloud.common.base.model.po.SysRole;
import com.moss.cloud.common.core.model.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自定义 UserDetails
 *
 * @author 瑾年
 * @date 2023年3月6
 */
@Service("userDetailsService")
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private IAuthorizationService authorizationService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        UserInfo userInfo = sysUserService.userInfo(username);
        AuthHandel.trueThrow(authorizationService.isBlocked(username)).throwMessage(AuthErrorType.PASSWORD_EXC_NUM.getCode());
        return new UserPrincipal(userInfo, obtainGrantedAuthorities(userInfo));
    }

    /**
     * 获得登录者所有角色的权限集合.
     *
     * @param userInfo
     * @return
     */
    private Set<GrantedAuthority> obtainGrantedAuthorities(UserInfo userInfo) {
        Set<SysRole> roles = new HashSet<>(sysRoleService.queryUserRolesByUserId(userInfo.getId()));
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getCode()))
                .collect(Collectors.toSet());
    }
}
